package services

import (
	"GOPAAS/internal/app/model"
	"GOPAAS/internal/utils"
	"database/sql"
	"fmt"
	"time"
)

type MailMessageService struct {
	model.MailMessage
}

func GetMessageService(m_id int64) *MailMessageService {
	db = getDB()
	var msg model.MailMessage
	if m_id > 0 {
		db.First(&msg, m_id)
	}
	return &MailMessageService{msg}
}

type MsgItem struct {
	Body       string   `json:"body"`
	UserId     int64    `json:"user_id"`
	UserName   string   `json:"user_name"`
	Profile    string   `json:"profile"`
	CreateDate string   `json:"create_date"`
	DateBeauty string   `json:"date_beauty"`
	Tracks     []string `json:"tracks"`
}

// GetMessageList 消息列表
func GetMessageList(model_name string, res_id int64, page int, limit int) (result []MsgItem, err error) {
	db = getDB()
	var msg []model.MailMessage
	var offset int
	offset = (page - 1) * limit
	res := db.Preload("Tracks").Preload("Partner").Where("model=? and res_id=?", model_name, res_id).Order("date desc").Offset(offset).Limit(limit).Find(&msg)
	if res.Error != nil {
		err = res.Error
		return
	}
	for _, v := range msg {
		var tracks = make([]string, 0)
		for _, vv := range v.Tracks {
			var t_msg string
			if utils.StringInArray([]string{"many2one", "selection", "char"}, vv.FieldType) {
				t_msg = fmt.Sprintf("%s:%s-%s", vv.FieldDesc, vv.OldValueChar, vv.NewValueChar)
			} else if utils.StringInArray([]string{"monetary"}, vv.FieldType) {
				t_msg = fmt.Sprintf("%s:%f-%f", vv.FieldDesc, vv.OldValueMonetary, vv.NewValueMonetary)
			} else if utils.StringInArray([]string{"boolean"}, vv.FieldType) {
				t_msg = fmt.Sprintf("%s:%d-%d", vv.FieldDesc, vv.OldValueInteger, vv.NewValueInteger)
			} else if utils.StringInArray([]string{"float"}, vv.FieldType) {
				t_msg = fmt.Sprintf("%s:%f-%f", vv.FieldDesc, vv.OldValueFloat, vv.NewValueFloat)
			} else if utils.StringInArray([]string{"text"}, vv.FieldType) {
				t_msg = fmt.Sprintf("%s:%s-%s", vv.FieldDesc, vv.OldValueText, vv.NewValueText)
			}
			tracks = append(tracks, t_msg)
		}
		result = append(result, MsgItem{
			Body:       v.Body,
			UserId:     v.CreateUid,
			UserName:   v.Partner.Name,
			Profile:    GetImage(128, "res.partner", v.AuthorId),
			CreateDate: utils.NullTimeValueFormat(v.Date, "2006-01-02 15:04:05"),
			DateBeauty: utils.BeautifyDate(v.Date.Time),
			Tracks:     tracks,
		})
	}
	return
}

// AddFocusUserIds 添加关注
func AddFocusUserIds(res_model string, res_id int64, user_ids []int64) (err error) {
	db = getDB()
	db.Where("res_model=? and res_id=?", res_model, res_id).Delete(&model.MailFollowers{})
	var res []model.MailFollowers
	for _, v := range user_ids {
		user_service := GetUserService(v)
		res = append(res, model.MailFollowers{
			ResModel:  res_model,
			ResId:     res_id,
			PartnerId: user_service.PartnerId,
		})
	}
	err = db.Create(&res).Error
	return
}

// MessageComment 通用评论
func MessageComment(res_model string, res_id int64, login_user_id int64, parent_id int64, comment string, msg_type string) (err error) {
	db = getDB()
	var ir_model model.IrModel
	var user model.ResUsers
	db.First(&user, login_user_id)
	db.Where("model=?", res_model).First(&ir_model)
	var comm model.MailMessage
	comm.Model = res_model
	//comm.ModelName = ir_model.Id
	comm.ResId = res_id
	comm.MessageType = msg_type
	comm.Date = sql.NullTime{time.Now(), true}
	comm.ParentId = utils.NullInt64Value(parent_id)
	comm.Body = comment
	comm.CreateUid = login_user_id
	comm.WriteUid = login_user_id
	comm.SubtypeId = 2
	comm.AuthorId = user.PartnerId
	err = db.Select("Model", "ResId", "MessageType", "Date", "ParentId", "Body", "CreateUid", "WriteUid", "SubtypeId", "AuthorId").Save(&comm).Error
	return
}

// SystemLog 系统日志
func SystemLog(res_model string, res_id int64, login_user_id int64, comment string) (err error) {
	//var user model.ResUsers
	//db.Preload("Partner").First(&user,login_user_id)
	//content := user.Partner.Name+" "+comment
	err = MessageComment(res_model, res_id, login_user_id, 0, comment, "notification")
	return
}

// MsgCommentLists 评论
func MsgCommentLists(model_name string, res_id int64, page int, limit int) (result []CommentItem, err error) {
	db = getDB()
	var comments []model.MailMessage
	offset := (page - 1) * limit
	q := db.Where("model=? and res_id=?", model_name, res_id).Where("parent_id is null")
	q.Preload("Partner").Order("create_date desc").Offset(offset).Limit(limit).Find(&comments)
	for _, v := range comments {
		var childs []model.MailMessage
		var child_item = make([]CommentChildItem, 0)
		db.Preload("Partner").Model(&model.MailMessage{}).Where("parent_id=?", v.Id).Order("create_date desc").Find(&childs)
		for _, vv := range childs {
			child_item = append(child_item, CommentChildItem{
				Id:         vv.Id,
				Comment:    vv.Body,
				Author:     vv.Partner.Name,
				Date:       vv.CreateDate.Format("2006-01-02 15:04:05"),
				HeaderImg:  GetImage(128, "res.partner", v.AuthorId),
				DateBeauty: utils.BeautifyDate(vv.CreateDate),
			})
		}
		result = append(result, CommentItem{
			Id:          v.Id,
			Comment:     v.Body,
			Author:      v.Partner.Name,
			HeaderImg:   GetImage(128, "res.partner", v.AuthorId),
			Date:        v.CreateDate.Format("2006-01-02 15:04:05"),
			DateBeauty:  utils.BeautifyDate(v.CreateDate),
			CommentNums: len(childs),
			Children:    child_item,
		})
	}
	return
}
